package com.dynabook.ems.disruptor.Excel;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.lmax.disruptor.dsl.Disruptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
@Slf4j
public class EmsDisruptorConfig {

    @Resource
    private EmsEventHandler emsEventHandler;

    @Resource
    private CustomExceptionHandler customExceptionHandler;

    @Bean("emsDisruptor")
    public Disruptor<EmsDataEvent> emsDisruptor() {
        // 定义环形大小
        int bufferSize = 1024 * 1024;
        Disruptor<EmsDataEvent> emsDisruptor = new Disruptor<>(
                new EmsEventFactory(),
                bufferSize,
                ThreadFactoryBuilder.create().setNamePrefix("emsDisruptor").build()
        );
        emsDisruptor.setDefaultExceptionHandler(customExceptionHandler);
        emsDisruptor.handleEventsWithWorkerPool(emsEventHandler);
        emsDisruptor.start();
        return emsDisruptor;
    }

    // 添加一个方法来重启Disruptor
    public void restartDisruptor(Disruptor<EmsDataEvent> disruptor) {
        disruptor.shutdown();
        disruptor.handleEventsWithWorkerPool(emsEventHandler);
        disruptor.start();
        log.info("Disruptor restarted with worker pool.");
    }
}